from . import passport_blue
from info.utils.captcha.captcha import captcha

from flask import request,jsonify,current_app
from info.utils.response_code import RET

from info import redis_store,constants
import re





@passport_blue.route('/image_code')

def generate_image_code():


    image_code_id = request.args.get('image_code_id')
    if not image_code_id:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
        name,text,image = captcha.generate_captcha()
        try:
            redis_store.setex('ImageCode_' + image_code_id,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='存储数据失败')
        else:
            response = make_response(image)
            return response
@passport_blue.route('/sms_code',methods=['POST'])
def send_sms_code():

    mobile = request.json.get('mobile')
    image_code = request.json.get('image_code')
    image_code_id = request.json.get('image_code_id')
    if not all([mobile,image_code,image_code_id]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数缺失')
    if not re.match(r'1[3456789]\d{9}$'.mobile):
        return jsonify(errno=RET.PARAMERR,errmsg='手机号格式错误')
    try:
        real_image_code = redis_store.get('ImageCode_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据失败')
    if not real_image_code:
        return jsonify(errno=RET.NODATA,errmsg='图片验证码已过期')
    try:
        redis_store.delete('ImageCode_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR,errmsg='图片验证码错误')










    pass